<?php

namespace App\Admin\Forms\Aliyun;

use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Dcdn\Dcdn;
use App\Enums\BucketType;
use App\Enums\DnsType;
use App\Enums\DomainSource;
use App\Enums\DomainType;
use App\Facades\AliyunDns;
use App\Jobs\CreateAliyunDcdn;
use App\Models\Aliyun;
use App\Models\DomainPool;
use App\Models\ObjectStorageService;
use Dcat\Admin\Admin;
use Dcat\Admin\Exception\RuntimeException;
use Dcat\Admin\Http\JsonResponse;

class StatementDomainForm extends DcdnForm
{
    /**
     * @throws ServerException
     * @throws ClientException
     */
    public function handle(array $input): JsonResponse
    {
        if ($input['source'] == DomainSource::ALIYUN->value) {
            if (DomainPool::where('domain', $input['rr'].'.'.$input['root'])->exists()) {
                return $this->response()->error('域名必须全局唯一');
            }

            if ($input['aliyun_id'] != ObjectStorageService::ofAdmin()->find($input['oss_id'])->aliyun_id) {
                ObjectStorageService::ofAdmin()->find($input['oss_id'])->aliyun->initClient();
                try {
                    Dcdn::v20180115()
                        ->verifyDcdnDomainOwner()
                        ->withDomainName($input['rr'].'.'.$input['root'])
                        ->withVerifyType('dnsCheck')
                        ->request();
                } catch (ClientException|ServerException) {
                    $content = Dcdn::v20180115()
                        ->describeDcdnVerifyContent()
                        ->withDomainName($input['rr'].'.'.$input['root'])
                        ->request()
                        ->get('Content');

                    AliyunDns::aliyun(Aliyun::ofAdmin()->find($input['aliyun_id']))
                        ->store($input['root'], 'verification', $content, DnsType::TXT);
                }
            }

            $data = [
                'source' => $input['source'],
                'aliyun_id' => $input['aliyun_id'],
                'type' => DomainType::STATEMENT,
                'domain' => $input['rr'].'.'.$input['root'],
                'rr' => $input['rr'],
                'root' => $input['root'],
                'oss_id' => $input['oss_id'],
                'status' => $input['status'],
                'ssl' => $input['ssl'],
            ];
        } else {
            $domain = $input['domain'];
            if (DomainPool::where('domain', $domain)->exists()) {
                return $this->response()->error('域名必须全局唯一');
            }
            $data = [
                'source' => $input['source'],
                'type' => DomainType::STATEMENT,
                'domain' => $domain,
                'status' => $input['status'],
                'ssl' => $input['ssl'],
            ];
        }

        if (Admin::user()->isAdministrator()) {
            $data['application_id'] = $input['application_id'];
        }

        $pool = DomainPool::ofAdmin()->create($data);

        if ($input['source'] == DomainSource::ALIYUN->value) {
            CreateAliyunDcdn::dispatch($pool);
        }

        return $this->response()->success('操作成功')->refresh();
    }

    /**
     * @throws RuntimeException
     */
    public function form(): void
    {
        $this->baseForm(BucketType::STATEMENT);
    }
}
